package qiniu

import (
	"context"
	"fmt"
	"gitee.com/wuennan/cloudstation/store"
	"github.com/go-playground/validator/v10"
	"github.com/k0kubun/go-ansi"
	"github.com/qiniu/go-sdk/v7/auth/qbox"
	"github.com/qiniu/go-sdk/v7/storage"
	"github.com/schollz/progressbar/v3"
)

var validate = validator.New()

type qiniu struct {
	ak   string `validate:"required"`
	sk   string `validate:"required"`
	//zone string `validate:"required"`
}

func NewUploader(ak, sk string) (store.Uploader, error) {
	upload := &qiniu{
		ak:   ak,
		sk:   sk,
		//zone: zone,
	}
	err := upload.validate()
	if err != nil {
		return nil, err
	}
	return upload, nil
}

func (q *qiniu) validate() error {
	return validate.Struct(q)
}

func (q *qiniu) UploadFile(bucketName, objectKey, filePath string) error {
	putPolicy := storage.PutPolicy{
		Scope: bucketName,
	}
	mac := qbox.NewMac(q.ak, q.sk)
	upToken := putPolicy.UploadToken(mac)
	cfg := storage.Config{}
	// 空间对应的机房
	//cfg.Zone = &storage.q.zone
	cfg.Zone = &storage.ZoneHuabei
	// 是否使用https域名
	cfg.UseHTTPS = false
	// 上传是否使用CDN上传加速
	cfg.UseCdnDomains = false
	// 构建表单上传的对象
	formUploader := storage.NewFormUploader(&cfg)
	ret := storage.PutRet{}
	// 可选配置
	putExtra := storage.PutExtra{
		Params: map[string]string{
			"x:name": "github logo",
		},
		// fsize为文件大小，uploaded为已上传的大小
		OnProgress: func(fsize, uploaded int64)  {
			q.listener(fsize, uploaded)
		},
	}
	err := formUploader.PutFile(context.Background(), &ret, upToken, objectKey, filePath, &putExtra)
	if err != nil {
		return err
	}

	// 打印下载连接
	domain := "http://qwy7zg89i.hb-bkt.clouddn.com"
	publicAccessURL := storage.MakePublicURL(domain, objectKey)
	fmt.Printf("\n下载链接: %s\n", publicAccessURL)
	fmt.Println("\n注意: 文件下载有效期为1天, 中转站保存时间为3天, 请及时下载")

	//fmt.Println(putExtra.OnProgress)
	return nil
}

func (q *qiniu)listener(fsize,uploaded int64) error {
	bar := progressbar.NewOptions64(fsize,
		progressbar.OptionSetWriter(ansi.NewAnsiStdout()),
		progressbar.OptionEnableColorCodes(true),
		progressbar.OptionShowBytes(true),
		progressbar.OptionSetWidth(30),
		progressbar.OptionSetDescription("开始上传:"),
		progressbar.OptionSetTheme(progressbar.Theme{
			Saucer:        "=",
			SaucerHead:    ">",
			SaucerPadding: " ",
			BarStart:      "[",
			BarEnd:        "]",
		}),
	)
	err := bar.Add64(uploaded)
	if err !=nil{
		return err
	}
	return nil
}